package com.lwl.office.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.lwl.office.api.vo.UploadResult;
import com.lwl.office.webeditor.Html2WordConvert;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/")
public class ApiController {
    @Value("${file.store.path}")
    private String folderPath;

    /**
     * 获取文件上传的配置信息
     * @param action
     * @return
     */
    @GetMapping("callback")
    public JSONObject editorGetCallback(String action){
        return JSONObject.parseObject(ResourceUtil.readUtf8Str("editor-config.json"));
    }

    /**
     * 处理图片、文件、涂鸦等上传
     * @param action
     * @param scrawl
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("callback")
    public UploadResult editorPostCallback(String action,String scrawl, MultipartFile file) throws IOException {
        UploadResult result = new UploadResult();
        switch (action){
            case "uploadscrawl":
                uploadScrawl(scrawl,result);
                break;
            default:
                uploadFile(file,result);
        }
        return result;
    }

    /**
     * 上传图片、文件、视频等
     * @param file
     * @param result
     */
    private void uploadFile(MultipartFile file, UploadResult result) throws IOException {
        String filePath = folderPath+file.getOriginalFilename();
        File f = new File(filePath);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }
        if(!f.exists()){
            f.createNewFile();
        }
        InputStream in = file.getInputStream();
        OutputStream out = new FileOutputStream(filePath);
        StreamUtils.copy(in,out);
        out.flush();
        out.close();
        in.close();

        result.setUrl(filePath);
        result.setOriginal(file.getName());
        result.setType(file.getContentType());
        result.setSize(file.getSize());
    }

    /**
     * 上传涂鸦
     * @param scrawl
     * @param result
     */
    private void uploadScrawl(String scrawl, UploadResult result) throws IOException {
        String filename = UUID.randomUUID() +".png";
        String filePath = folderPath+ filename;
        File f = new File(filePath);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }
        if(!f.exists()){
            f.createNewFile();
        }
        Base64.decodeToFile(scrawl,f);
        result.setUrl(filePath);
        result.setOriginal(filename);
        result.setType("png");
        result.setSize(FileUtil.size(f));
    }

    /**
     * 下载文件
     * @param path
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void download(String path, HttpServletResponse response) throws IOException {
        String filename = path.substring(path.lastIndexOf(File.pathSeparator)+1);
        File file = new File(path);
        response.setContentType("application/*");
        response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream fis = new FileInputStream(file);
        int j = 0;
        byte[] buffer = new byte[1024];
        while((j = fis.read(buffer)) > 0){
            out.write(buffer, 0, j);
        }
        // 关闭流
        fis.close();
        if(out!=null){
            out.flush();
            out.close();
        }
    }

    /**
     * 生成word
     * @param html
     * @throws IOException
     */
    @PostMapping("generateWord")
    public UploadResult html2word(@RequestBody String html) throws IOException {
        XWPFDocument convert = Html2WordConvert.convert(html);
        String filename = UUID.randomUUID()+".docx";
        String filePath = folderPath+"generate"+File.pathSeparator+filename;
        File store = new File(filePath);
        if(!store.getParentFile().exists()){
            store.getParentFile().mkdirs();
        }
        if(!store.exists()){
            store.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(store);
        convert.write(out);
        out.flush();
        out.close();
        convert.close();
        UploadResult result = new UploadResult();
        result.setUrl(filePath);
        result.setType("docx");
        return result;
    }
}
